#!/usr/bin/perl 
#===============================================================================
#
#         FILE:  buildpac.pl
#
#        USAGE:  ./buildpac.pl  
#
#  DESCRIPTION:  
#
#      OPTIONS:  ---
# REQUIREMENTS:  ---
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:  huangwei, huangwei.bupt@gmail.com
#      COMPANY:  BUPT
#      VERSION:  1.0
#      CREATED:  09/29/2010 12:05:40 PM
#     REVISION:  ---
#===============================================================================

use warnings;
use strict;
use POSIX qw(strftime);
use File::Spec;

# =========== Edit Below As Your Will =====================

my $src  = "autoproxy.src"; # file downloaded from $url, rename it anyway 
my $ua   = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.10) Gecko/20090909 Ubuntu/10.04 (lucid) Firefox/3.6.10"; # cheat with appspot.com
my $url  = "http://autoproxy2pac.appspot.com/pac/proxy/127.0.0.1/8118?download"; # replace it with your pac download url
my $lst  = "wfg.lst"; # base64 decoded original pac file
my $tmp  = "wfg.tmp"; # only temp file, rename it anyway
my $out  = "autoproxy.pac"; # your preferred final pac file name
my $start = 9; # extract from this line of $lst
my $end   = 2; # extract until the bottom of this line of $lst
my $freq = 60 * 60 *24; # update frequency, default to 1 day
my $min_file_size = 1024; # minimum file size that should be considered "empty" file

my @head_1 = <<_AUTOPROXY_HEAD_1_;
/*
 * Proxy Auto-Config file generated by autoproxy2pac
 *  Rule source: http://autoproxy-gfwlist.googlecode.com/svn/trunk/gfwlist.txt
_AUTOPROXY_HEAD_1_

my $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;

my $ts = "*  Last update: $now_string";

my @head_2 = <<_AUTOPROXY_HEAD_2_;
 *  Modified by huangwei.bupt\@gmail.com
 */
function FindProxyForURL(url, host) {
  PROXY = "PROXY 127.0.0.1:8118"; //本地代理地址，一般可以通过SSH Tunnel或者VPN或者TOR的方式建立
//  PROXY = "PROXY gfw-proxy.co.cc:3128"; //IPv6用户可以使用这个地址
//

  // BUPT proxy list
  BUPT_PROXY = "PROXY iproxy.bupt.edu.cn:8080";
  if (shExpMatch(myIpAddress(), "59.64.*")  //\@BUPT LAB ipv4 and ipv6
  )  
{
  DEFAULT = BUPT_PROXY;

  if(/\.cnki\.net/i.test(url))  return "DIRECT";
  if(/\.ieee\.org/i.test(url)) return "DIRECT";
  if(/\.sciencedirect\.com/i.test(url)) return "DIRECT";
  if(/\.edu\.cn/i.test(url)) return "DIRECT";
  if(/\.springerlink\.com/i.test(url)) return "DIRECT";
  if(/\.isiknowledge\.com/i.test(url)) return "DIRECT";
  if(/\.byr\.cn/i.test(url)) return "DIRECT";
  if(/\.engineeringvillage2\.org\.cn/i.test(url)) return "DIRECT";
  if(/\.newsmth\.net/i.test(url)) return "DIRECT"; 

}
else if (shExpMatch(myIpAddress(), "10.2.1.*")  //\@CUC LAB ipv4 and ipv6
  )  
{

  DEFAULT = "DIRECT";

  if(/\.bupt\.edu\.cn/i.test(url)) return BUPT_PROXY;
  if(/\.cnki\.net/i.test(url))  return BUPT_PROXY;
  if(/\.ieee\.org/i.test(url)) return BUPT_PROXY;
  if(/\.sciencedirect\.com/i.test(url)) return BUPT_PROXY;
  if(/\.springerlink\.com/i.test(url)) return BUPT_PROXY;
  if(/\.engineeringvillage2\.org\.cn/i.test(url)) return BUPT_PROXY;

}else{ // \@ADSL

  DEFAULT = "DIRECT";

  if(/\.bupt\.edu\.cn/i.test(url)) return BUPT_PROXY;
  if(/\.cnki\.net/i.test(url))  return BUPT_PROXY;
  if(/\.ieee\.org/i.test(url)) return BUPT_PROXY;
  if(/\.sciencedirect\.com/i.test(url)) return BUPT_PROXY;
  if(/\.springerlink\.com/i.test(url)) return BUPT_PROXY;
  if(/\.engineeringvillage2\.org\.cn/i.test(url)) return BUPT_PROXY;

}

_AUTOPROXY_HEAD_2_

my @tail = <<_AUTOPROXY_TAIL_;

  if(host == "p.p" || dnsDomainIs(host, "config.privoxy.org")) return PROXY;

  return DEFAULT;
}
_AUTOPROXY_TAIL_

# =========== Edit Above As Your Will =====================

my $wget = "wget -O ".$src." -U '".$ua."' $url";

if( -f $src && (stat($src))[7] > $min_file_size )
{
	my $mtime = (stat($src))[9]; # get file mtime
	my $nowsec = time(); # get current time
	my $intval = $nowsec - $mtime;
	if($intval > $freq )
	{
		system($wget) == 0 or die "wget error: $!";
	}

}
else
{
# execute wget to fetch the up2date g*f*wlist
	system($wget) == 0 or die "wget error: $!";
}

open SRCFILE, "<$src" or die $!;
my @lines = <SRCFILE>;
foreach my $line ( @lines )
{
	if( $line =~ m/(decode64\(\")([\w\d\/+=]*)/g )	
	{
		open TMPFILE, ">$tmp" or die $1;
		print TMPFILE $2;	
		close TMPFILE;
	}

	if(system("base64 -d ".$tmp." > $lst") == 0)
	{
		unlink $tmp;	
	}
	else
	{
		die "base64 decode error: $!";
	}
}

close SRCFILE;

if( -f $lst && (stat($lst))[7] > $min_file_size )
{
	open SRCFILE, "<$lst" or die $1;
	open DSTFILE, ">$out" or die $1;
	my @lines = <SRCFILE>;
	my $line;

# print head of autoproxy.pac
	foreach $line (@head_1)
	{
		print DSTFILE $line;
	}

	print DSTFILE $ts, "\n";

	foreach $line (@head_2)
	{
		print DSTFILE $line;
	}

	for(my $line_num = $start; $line_num < $#lines - $end; $line_num ++)
	{
		print DSTFILE $lines[$line_num];
	}

	foreach $line (@tail)
	{
		print DSTFILE $line;
	}

	close DSTFILE;
	close SRCFILE;

	unlink $lst;
	printf "%s\nfile://%s\n", "Copy the following URL into your proxy_url", File::Spec->rel2abs($out);
}



